import {resetLongToStr} from "@/utils/biz/common/BizUtils";
import {UserCommitApi} from "@/api/user_common";
import {UserWaitApi} from "@/api/user_api";
class AndroidLocalSdkUtil {
  constructor(_this) {
    this.catcheInfo = _this;
  }

  /**
   * 模拟安卓收消息
   * action：入口
   * callback:前端回调
   * bizFun：业务方法
   * @param msgStr
   */
  async handleMessage(msgStr) {
    let self = this.catcheInfo;
    let msgObj = JSON.parse(msgStr);
    switch (msgObj.action) {
      case "CommonAction":
        switch (msgObj.bizFun) {
          case "getDeviceInfo":
            await this.sendSbInfoMsg(msgObj);
            break;
          case "setHtmlLog":
            this.setHtmlLog(msgObj);
            break;
          case "templateCall":
            this.playMark(msgObj);
            break;
        }
        break;
      case "ReportMachineAction":
        switch (msgObj.bizFun) {
          case "reportQuery":
            await this.initSign(msgObj);
            break;
          // 报到操作
          case "report":
            await this.report(msgObj.data);
            break;
          case "takeNumberTicket":
            // 打印小票
            await this.takeNumberTicket(msgObj.data);
            break;
          case "reprintTicket":
            // 打印小票
            await this.reprintTicket(msgObj.data);
            break;

          case "batchSignResult":
            // 打印小票
            await this.takeNumberTicketBatch(msgObj.data);
            break;
        }

        break;
      case "QueueSwitchAction":
        // 候诊屏获取
        const {pageSize, switchSeconds, queryRule, dataSource} = JSON.parse(msgObj.data);
        this.catcheInfo.pageSize = pageSize || 5;
        this.catcheInfo.switchSeconds = switchSeconds || 10000;
        this.catcheInfo.queryRule = queryRule || "1";
        // 0表示门诊 1 第三方 2 其他
        this.catcheInfo.dataSource = dataSource || 0;
        await this.WaitList();
        // 数据分组
        await this.getGroupData();
        // 初始化定时器
        await this.initTimerTask();
        break;


    }
  }

  /**
   * 语音播报
   * @param msgData
   */
  playMark(obj) {
    const msgData = JSON.parse(resetLongToStr(obj.data));
    let msgContent = msgData.msgContent;
    let voiceArr = [];
    let bizType = msgData.msgCode;
    // 就诊语音播放
    if (msgContent.treatingVoice && msgContent.treatingVoicePlayUrl) {
      let treatingVoiceCount = msgContent.treatingVoiceCount || 1;
      const number = Number(treatingVoiceCount);
      for (let i = 0; i < number; i++) {
        if (msgContent.treatingVoicePlayUrl != "") {
          voiceArr.push({
            path: msgContent.treatingVoicePlayUrl
          });
        }
      }
    }
    // 候诊语音播放
    if (msgContent.waitingVoice && msgContent.waitingVoicePlayUrl) {
      let waitingVoiceCount = msgContent.waitingVoiceCount || 1;
      const number = Number(waitingVoiceCount);
      for (let i = 0; i < number; i++) {
        if (msgContent.waitingVoicePlayUrl != "") {
          voiceArr.push({
            path: msgContent.waitingVoicePlayUrl
          });
        }
      }
    }
    // 候诊弹窗 就诊弹窗
    if ((msgContent.waitingAlert || msgContent.treatingAlert)) {
      window.webSDKServices({
        bizType: "openMsgWin",
        msgContent: JSON.stringify(msgData)
      });
    }
    // 配置是否展示就诊弹窗/候诊弹窗
    let elem = this.catcheInfo.$refs.audio;
    let start = 0;
    elem.src = voiceArr[start].path;
    elem.addEventListener("ended", function () {
      start++;
      if (start < voiceArr.length) {
        elem.src = voiceArr[start].path;
        if (elem.paused) {
          elem.play();
        } else {
          elem.pause();
        }
      } else {
        start = 0;
        voiceArr = [];
        // 关闭弹窗
        window.webSDKServices({
          bizType: "closeMsgWin",
          msgContent: ""
        });
      }
    });
    elem.play();
  }
  /**
   * 打印日志
   * @param msgObj
   */
  setHtmlLog(msgObj) {
    // console.table(msgObj);
  }

  /**
   * 发送时间消息
   */
  sendSetDateMsg(data) {
    window.webSDKServices({
      bizType: "setDate",
      msgContent: JSON.stringify(data)
    });
  }

  /**
   * 获取设备信息
   */
  async getSbInfo() {
    var formData = {};
    formData.terminalId = this.catcheInfo.terminalId;
    formData.terminalType = this.catcheInfo.terminalType;
    const {data} = await UserCommitApi.getSbInfo(formData);
    if (this.catcheInfo.terminalType == "1") {
      this.catcheInfo.sbInfo = {
        terminalId: data.signMachineId,
        terminalType: "1",
        businessType: data.signMachineType,
        tenantId: "000000",
        deviceName: data.signMachineName,
        ip: data.signMachineIp,
        onlineStatus: data.onlineStatus,
        mac: data.signMachineMac,
        ruleType: data.ruleType
      };
    } else if (this.catcheInfo.terminalType == "8") {
      this.catcheInfo.sbInfo = {
        terminalId: data.selfMachineId,
        terminalType: "8",
        businessType: data.businessType,
        tenantId: "000000",
        deviceName: data.selfMachineName,
        ip: data.selfMachineIp,
        onlineStatus: data.onlineStatus,
        mac: data.selfMachineMac,
        ruleType: data.ruleType
      };
    } else {
      this.catcheInfo.sbInfo = {
        terminalId: data.lcdId,
        terminalType: data.lcdType,
        businessType: data.businessType,
        tenantId: "000000",
        deviceName: data.lcdName,
        relationList: data.relationList,
        ip: data.lcdIp,
        onlineStatus: data.onlineStatus,
        mac: data.lcdMac,
        ruleType: data.ruleType
      };
    }
    if (data.volume) {
      this.catcheInfo.volume = data.volume;
    }
    if (data.volume) {
      this.catcheInfo.waitNum = data.waitNum;
    }
    // if (iForm("sign_in_form", formData)) {
    //
    // }
  }

  async getVirtualSb() {
    // 获取虚拟设备
    const {data, code} = await UserCommitApi.getVirtualSb(this.catcheInfo.sbInfo);
    if (code == 200) {
      this.catcheInfo.virtualSbInfo = data;
    }
  }

  /**
   * 给前端发送设备信息
   * @param msgObj
   * @returns {Promise<void>}
   */
  async sendSbInfoMsg(msgObj) {
    let relationList = this.catcheInfo.sbInfo.relationList;
    let zsName = "";
    if (relationList && relationList.length > 0) {
      zsName = relationList[0].relationTargetName || "暂无诊室";
    }
    window.webSDKServices({
      bizType: msgObj.callback,
      msgContent: JSON.stringify({
        screenId: this.catcheInfo.sbInfo.terminalId,
        screenType: this.catcheInfo.sbInfo.terminalType,
        businessType: this.catcheInfo.sbInfo.businessType,
        hospitalId: this.catcheInfo.sbInfo.tenantId || "000000",
        waitNum: this.catcheInfo.sbInfo.waitNum || 3,
        deviceName: this.catcheInfo.sbInfo.deviceName,
        ip: this.catcheInfo.sbInfo.ip,
        zsName: zsName,
        mac: this.catcheInfo.sbInfo.mac,
        ruleType: this.catcheInfo.sbInfo.ruleType
      })
    });

  }

  /**
   * 获取全量医生ID
   */
  async WaitList() {
    let formData = {
      terminalId: this.catcheInfo.sbInfo.terminalId,
      terminalType: this.catcheInfo.sbInfo.terminalType,
      businessType: this.catcheInfo.sbInfo.businessType,
      tenantId: this.catcheInfo.sbInfo.tenantId,
      queryRule: this.catcheInfo.queryRule,
      dataSource: this.catcheInfo.dataSource
    };
    const {data} = await UserWaitApi.getWaitList(formData);
    this.catcheInfo.workerIds = data || [];
  }

  /**
   * 医生信息分组
   */
  async getGroupData() {
    // 获取分组数据
    let groupData = this.groupBy(this.catcheInfo.workerIds, this.catcheInfo.pageSize);
    this.catcheInfo.groupData = groupData;
  }


  //分组
  groupBy(arr, groupSize) {
    if (!arr || arr.length == 0) {
      return [];
    }
    let tempAllArr = [];
    let tempArr = [];
    arr.forEach((item, index) => {
      tempArr.push(item);
      if (index > 0 && index % (groupSize - 1) === 0) {
        tempAllArr.push(tempArr);
        tempArr = [];
      } else {
        if (index === arr.length - 1) {
          tempAllArr.push(tempArr);
        }
      }
    });
    return tempAllArr;
  }

  /**
   * 获取模板详情
   */
  async getModelDetail() {
    let formData = {
      screenId: this.catcheInfo.sbInfo.terminalId,
      screenType: this.catcheInfo.sbInfo.terminalType,
      tenantId: this.catcheInfo.sbInfo.tenantId,
    };
    // 获取模板详情
    const {data} = await UserCommitApi.getModelDetail(formData);
    this.catcheInfo.moduleInfo = data;
  }

  /**
   * 获取模板详情
   */
  async getScreenLocalTemplate() {
    let formData = {
      localModelId: this.catcheInfo.localModelId
    };
    // 获取模板详情
    const {data} = await UserCommitApi.getScreenLocalTemplate(formData);
    this.catcheInfo.moduleInfo = data;
  }


  /**
   * 发送候诊屏 刷新候诊列表
   */
  sendUpdateWaitScreenDoctors(data) {
    window.webSDKServices({
      bizType: "updateWaitScreenDoctors",
      msgContent: JSON.stringify(data)
    });
  }

  async report(params) {
    params = JSON.parse(params);
    if (params.isBatch === true) {
      await this.batchAction(params);
    } else {
      await this.signAction(params);
    }
  }
  // 打印小票，获取打印小票接口
  async takeNumberTicket(params) {
    params = JSON.parse(params);
    let formData = Object.assign({
      terminalId: this.catcheInfo.sbInfo.terminalId,
      terminalType: this.catcheInfo.sbInfo.terminalType,
      businessType: this.catcheInfo.sbInfo.businessType,
      tenantId: this.catcheInfo.sbInfo.tenantId,
    }, {
      signId: params.signId,
      ruleType: params.ruleType
    });
    // 获取模板详情
    const res = await UserCommitApi.signPrint(formData);
  }
  // 打印小票
  async reprintTicket(params) {
    params = JSON.parse(params);
    let formData = Object.assign({
      terminalId: this.catcheInfo.sbInfo.terminalId,
      terminalType: this.catcheInfo.sbInfo.terminalType,
      businessType: this.catcheInfo.sbInfo.businessType,
      tenantId: this.catcheInfo.sbInfo.tenantId,
    }, {
      signId: params.signId,
      ruleType: params.ruleType
    });
    // 获取模板详情
    const res = await UserCommitApi.signPrint(formData);
  }


  // 打印小票，获取打印小票接口
  async takeNumberTicketBatch(data) {
    data = JSON.parse(data).data;
    for (let i = 0; i < data.length; i++) {
      if (200 == data[i].status) {
        let formData = Object.assign({
          terminalId: this.catcheInfo.sbInfo.terminalId,
          terminalType: this.catcheInfo.sbInfo.terminalType,
          businessType: this.catcheInfo.sbInfo.businessType,
          tenantId: this.catcheInfo.sbInfo.tenantId,
        }, {
          signId: data[i].signId,
          ruleType: data[i].ruleType
        });
        // 获取模板详情
        const res = await UserCommitApi.signPrint(formData);
      }
    }

  }

  /**
   * 获取模板详情
   */
  async initSign(params) {
    let formData = {
      terminalId: this.catcheInfo.sbInfo.terminalId,
      terminalType: this.catcheInfo.sbInfo.terminalType,
      businessType: this.catcheInfo.sbInfo.businessType,
      tenantId: this.catcheInfo.sbInfo.tenantId,
      patientNo: params.data
    };
    // 获取模板详情
    const res = await UserCommitApi.initSign(formData);
    // 发送消息
    window.webSDKServices({
      bizType: "reportQuery",
      msgContent: JSON.stringify({
        serverResp: JSON.stringify(res),
        isFromRefresh: "",
      })
    });
  }
  /**
   * 获取模板详情
   */
  async batchAction(params) {
    let formData = {
      terminalId: this.catcheInfo.sbInfo.terminalId,
      terminalType: this.catcheInfo.sbInfo.terminalType,
      businessType: this.catcheInfo.sbInfo.businessType,
      tenantId: this.catcheInfo.sbInfo.tenantId,
      patientNo: params.patientNo,
      ruleType: "0",
      signActionData: params.signActionData || []
    };
    // 批量报到
    const res = await UserCommitApi.signBatchAction(formData);
    // 发送消息
    window.webSDKServices({
      bizType: "reportResult",
      msgContent: JSON.stringify(res)
    });
    if (res.code == "200") {
      await this.initSign({
        data: params.patientNo
      });
    }
  }
  /**
   * 单个报到
   */
  async signAction(params) {
    let formData = {
      terminalId: this.catcheInfo.sbInfo.terminalId,
      terminalType: this.catcheInfo.sbInfo.terminalType,
      businessType: this.catcheInfo.sbInfo.businessType,
      tenantId: this.catcheInfo.sbInfo.tenantId,
      patientNo: params.patientNo,
      ruleType: "0",
      registerId: params.signActionData[0].registerId,
      signId: params.signActionData[0].signId,
      signType: params.signActionData[0].signType,
      medicalWorker: {
        workerId: params.signActionData[0].workerId || "",
        workerName: params.signActionData[0].workerName || "",
        registerObjId: params.signActionData[0].registerObjId || "",
        registerObjName: params.signActionData[0].registerObjName || ""
      }
    };
    // 获取模板详情
    const res = await UserCommitApi.signAction(formData);
    // 发送消息
    window.webSDKServices({
      bizType: "reportResult",
      msgContent: JSON.stringify(res)
    });
    if (res.code == "200") {
      await this.initSign({
        data: params.patientNo
      });
    }
  }




  //重置
  clearTimerTask () {
    clearTimeout(this.catcheInfo.timerTask);
  }

  //重置
  resetTimerTask() {
    clearTimeout(this.catcheInfo.timerTask);
    this.startTimerTask();
  }

  //开始
  startTimerTask () {
    let _this = this;
    let catcheInfo = this.catcheInfo;
    if (this.catcheInfo.groupData.length > 0) {
      console.info("定时器正在执行：————————————");
      let index = 0;
      // 请求接口
      this.sendUpdateWaitScreenDoctors(catcheInfo.groupData[index] || []);
      index++;
      catcheInfo.timerTask = setInterval(function () {
        if (catcheInfo.groupData.length == 1) {
          index = 0;
        }
        if (catcheInfo.groupData.length - 1 > index) {
          index++;
        } else {
          index = 0;
        }
        // 请求接口
        _this.sendUpdateWaitScreenDoctors(catcheInfo.groupData[index] || []);
      }, catcheInfo.switchSeconds * 1000);
    } else {
      _this.sendUpdateWaitScreenDoctors([]);
    }
  }
  /**
   * 初始化定时器
   * @returns {Promise<void>}
   * @constructor
   */
  async initTimerTask() {
    // 关闭定时器
    await this.clearTimerTask();

    // 开启定时器
    await this.startTimerTask();
  }

}

export {AndroidLocalSdkUtil};
